import { useMemo, useState } from "react";
import { useProjectDetail } from "utils/project";
import { useUrlQueryParam } from "utils/useUrlQueryParam";
import { useSetSearchUrlParam } from "utils/useUrlQueryParam";

export const useProjectSearchParam = () => {
  const [param, setParam] = useUrlQueryParam(["name", "personId"]);
  return [
    useMemo(() => {
      return {
        ...param,
        personId: Number(param.personId) || undefined,
      };
    }, [param]),
    setParam,
  ] as const;
};

export const useProjectQueryKey = () => {
  const [params] = useProjectSearchParam();
  return ['projects', params]
}

export const useProjectModal = () => {
  const [{ projectCreate }, setProjectCreate] = useUrlQueryParam(['projectCreate'])
  const [{ editingProjectId }, setEditingProjectId] = useUrlQueryParam(['editingProjectId'])

  // 获取详情信息
  const { data: editingProject, isLoading } = useProjectDetail(
    Number(editingProjectId)
  );

  const setSearchParams = useSetSearchUrlParam();

  const open = () => {
    setProjectCreate({ projectCreate: true })
  }

  const close = () => setSearchParams({ projectCreate: "", editingProjectId: "" });
  
  const startEdit = (id: number) => {
    setEditingProjectId({ editingProjectId: id })
  }

  return {
    projectModalOpen: projectCreate === 'true' || Boolean(editingProjectId),
    open,
    close,
    startEdit,
    isLoading,
    editingProject
  }
}
